#include <iostream>
#include "head.h"


void Usage(const string& proc)
{
    cout << "\n\rUsage: " << proc << "serverip serverport\n" << endl;
}

// ./tcpclient serverip serverport
int main(int argc, char* argv[]) 
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        cerr << "sock errror" << endl;
        return 1;
    }

    // tcp客户端也要bind, 不过不需要显示绑定
    // 客户端发起connet的时候， 进行自动随机bind
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));   //转化完毕，server目标连接的服务器信息已经填写好了

    int n = connect(sockfd, (struct sockaddr*)&server, sizeof(server));
    if(n < 0)
    {
        cerr << "conect err..." << endl;
        return 2;
    }
 
    // 开始发消息了
    string message;
    while(true)
    {
        cout << "Please Enter@ ";
        getline(cin, message);

        write(sockfd, message.c_str(), message.size());
        
        char inbuffer[1024];
        int n = read(sockfd, inbuffer, sizeof(inbuffer));
        if(n > 0)
        {
            inbuffer[n] = 0;
            cout << inbuffer << endl;
        }
    }


    return 0;
}